package top.llove.typeHandler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import top.llove.utils.time.TimeUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * 数据库时间毫秒值转字符串
 *
 * @author: 幸会
 * @date: 2021/6/17 15:08
 * @email: 1846724873@qq.com
 * @description: 数据库时间毫秒值转字符串
 * version: 1.0
 */
@MappedJdbcTypes(JdbcType.DATE) // 数据库数据类型
@MappedTypes(String.class) // 映射的Java数据类型
public class DateToString implements TypeHandler<String> {

    @Override
    public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        Date date = new Date(parameter);
        ps.setDate(i, new java.sql.Date(date.getTime()));
    }

    @Override
    public String getResult(ResultSet rs, String columnName) throws SQLException {
        Date date = rs.getDate(columnName);
        return TimeUtils.getTime(date, "yyyy-MM-dd HH:mm:ss");
    }

    @Override
    public String getResult(ResultSet rs, int columnIndex) throws SQLException {
        Date date = rs.getDate(columnIndex);
        return TimeUtils.getTime(date, "yyyy-MM-dd HH:mm:ss");
    }

    @Override
    public String getResult(CallableStatement cs, int columnIndex) throws SQLException {
        Date date = cs.getDate(columnIndex);
        return TimeUtils.getTime(date, "yyyy-MM-dd HH:mm:ss");
    }
}
